/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets.friends;

import beans.user.UserBean;
import database.Database;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Stephen'sSSD
 */
public class FindFriendServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        int id = Integer.parseInt(request.getParameter("id"));
        Connection c = Database.getConnection();
        UserBean user = (UserBean) request.getSession().getAttribute("userBean");
        try {
            if (c != null) {
                try {
                    PreparedStatement ps = c.prepareStatement("INSERT INTO friend(user1Id, user2Id) VALUES(?,?)");
                    ps.setInt(2, id);
                    ps.setInt(1, user.getId());
                    try {
                        ps.executeUpdate();
                    } catch (SQLException e) { // Do nothing
                    }
                } catch (SQLException ex) {
                    //Logger.getLogger(FindFriendServlet.class.getName()).log(Level.SEVERE, null, ex);
                }
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // THIS IS COPY/PASTED CODE FROM GETFRIENDSSERVLET, PLEASE MODIFY THIS ALONG WITH THE GETFRIENDSSERVLET  //
                //////////////////////////////////////////////////////////////////////////////////////////////////////////
                try {
                    PreparedStatement s = c.prepareStatement("SELECT * FROM friend WHERE user1Id = ? OR user2Id = ?");
                    s.setInt(1, user.getId());
                    s.setInt(2, user.getId());
                    ResultSet rs = s.executeQuery();
                    while (rs.next()) {
                        int friendId = (rs.getInt("user2Id") == user.getId() ? rs.getInt("user1Id") : rs.getInt("user2Id"));
                        PreparedStatement ss = c.prepareStatement("SELECT * FROM user WHERE id = ?");
                        ss.setInt(1, friendId);
                        ResultSet rss = ss.executeQuery();
                        while (rss.next()) {
                            out.println("<div class='friendDiv'><span class='friend' title='" + rss.getInt("id") + "'>" + rss.getString("name")
                                    + "</span><input type='checkbox' name='friendCheckbox' class='friendCheckBox' value='" + rss.getInt("id") + "' /></div>");
                        }
                    }
                    out.println("<input type='button' id='addFriendToTripButton' value='Add to Trip' onclick='addFriendsToTrip()'/>");
                    out.println("<div id='addFriendDialog' class='invisible'><input id='friendEmail' type='text' value='Email' onfocus='clearBox()' onblur='refill()' onkeyup='findFriend()' />"
                            + "</div>");
                    out.println("<div id='friendsDisplay'></div>");
                    out.println("<input type='button' id='addFriendsButton' value='Find Friend' onclick='displayDialog()'/>"
                            + "<input id='closeButton' type='button' value='Close' onclick='closeDialog()' class='invisible'/>");
                    out.println("<br/><br/><br/><br/>");
                    out.println("<input id='deleteFriend' type='button' value='Delete' onclick='deleteFriend()'/>");
                } catch (SQLException ex) {
                    // Logger.getLogger(GetFriendsServlet.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } finally {
            out.close();
        }
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
